package com.jcfk.system.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jcfk.common.business.controller.BaseController;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.log.annotation.RequestLogHeader;
import com.jcfk.common.business.utils.DataBindHelper;
import com.jcfk.common.core.security.MyPasswordEncoder;
import com.jcfk.common.core.utils.ExcelUtils;
import com.jcfk.common.web.domain.*;
import com.jcfk.system.domain.dto.*;
import com.jcfk.system.domain.po.SysUser;
import com.jcfk.system.domain.query.SysLogQuery;
import com.jcfk.system.domain.query.SysUserQuery;
import com.jcfk.system.domain.uploadExcel.SysUserUploadExcel;
import com.jcfk.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理 服务接口
 */
@Api(value = "/sysUser", tags = {"用户管理 服务接口"})
@RestController
@RequestMapping("/sysUser")
@Slf4j
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询用户信息列表(分页)
     *
     * @param requestParam
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "ReqPageParam<SysUserQuery>", name = "requestParam", value = "", required = true)})
    @ApiOperation(value = "查询用户信息列表(分页)", notes = "查询用户信息列表(分页)", httpMethod = "POST")
    @PostMapping("queryByPage")
    public RetPage<SysUserDTO> queryByPage(@RequestBody ReqPageParam<SysUserQuery> requestParam) {
        DataPage<SysUserDTO> page = new DataPage<SysUserDTO>((long) requestParam.getCurrent(), (long) requestParam.getSize(), requestParam.getSort().getOrderItem(), SysUserDTO.class);
        page = sysUserService.queryByPage(page, requestParam.getData());

        for (SysUserDTO dto : page.getRecords()) {
            dto.setPassword(null);
        }

        // 绑定启用标志文本
        DataBindHelper.bindDataLabel(page.getRecords(), AvailableStatus.getMap(), "enabled", "enabledLabel");

        return new RetPage<SysUserDTO>(page);
    }

    /**
     * 查询用户信息列表
     *
     * @param sysUserQuery
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysUserQuery", name = "sysUserQuery", value = "", required = true)})
    @ApiOperation(value = "查询用户信息列表", notes = "查询用户信息列表", httpMethod = "POST")
    @PostMapping("getList")
    public RetResult<?> getList(@RequestBody SysUserQuery sysUserQuery) {
        List<SysUserDTO> list = sysUserService.getList(sysUserQuery);
        // 绑定启用标志文本
        DataBindHelper.bindDataLabel(list, AvailableStatus.getMap(), "enabled", "enabledLabel");
        return RetResult.ok(list);
    }

    /**
     * 添加/更新管理用户
     *
     * @param sysUser
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysUserDTO", name = "sysUser", value = "", required = true)})
    @ApiOperation(value = "添加/更新管理用户", notes = "添加/更新管理用户", httpMethod = "POST")
    @RequestLogHeader(modular = "用户管理", businessType = "保存")
    @PostMapping("/save")
    public RetResult<?> save(@RequestBody @Validated SysUserDTO sysUser) {
        // 数据校验
        RetResult ret = sysUserService.isValid(sysUser);
        if (!ret.getCode().equals(RetResult.SUCCESS)) {
            return ret;
        }

        if (StringUtils.isEmpty(sysUser.getUserType())) {
            sysUser.setUserType("ordinaryuser");
        }

        if (StrUtil.isEmpty(sysUser.getId())) {
            sysUser.setPassword(MyPasswordEncoder.getInstance().encode(sysUser.getPassword()));
            // 新增
            sysUserService.insert(sysUser);
            return RetResult.ok();
        } else {
            // 更新
            sysUser.setPassword(null);
            return RetResult.ok(sysUserService.update(sysUser));
        }
    }


    /**
     * 逻辑删除管理用户
     *
     * @param sysUser
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "List<SysUserDTO>", name = "list", value = "", required = true)})
    @ApiOperation(value = "逻辑删除管理用户", notes = "逻辑删除管理用户", httpMethod = "POST")
    @RequestLogHeader(modular = "用户管理", businessType = "删除")
    @PostMapping("/delete")
    public RetResult<?> deleteList(@RequestBody SysUserDTO sysUser) {
        return RetResult.ok(sysUserService.logicDeleteList(sysUser));
    }

    /**
     * 获取单一管理用户
     *
     * @param id
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "获取单一管理用户", notes = "获取单一管理用户", httpMethod = "POST")
    @GetMapping("/get/{id}")
    public RetResult<SysUserDTO> get(@NonNull @PathVariable("id") String id) {
        SysUserDTO sysUser = sysUserService.get(id);
        return RetResult.ok(sysUser);
    }

    /**
     * 获取单一管理用户
     *
     * @param sysUser
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "用户管理", notes = "重置密码", httpMethod = "POST")
    @PostMapping("/rest")
    public RetResult<?> rest(@RequestBody @Validated UserRestParameter sysUser) {
        sysUserService.rest(sysUser);
        return RetResult.ok();
    }

    /**
     * 根据组织机构筛选 用户
     *
     * @param requestParam
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "用户管理", notes = "获取用户", httpMethod = "POST")
    @PostMapping("/getLsitPage")
    public RetPage<SysUserVo> getListPage(@RequestBody ReqPageParam<UserOrganizationParameter> requestParam) {
        //设置默认排序
        if(requestParam.getSort().getOrderItem()==null){
            ReqSortParam<UserOrganizationParameter> sortParam=new ReqSortParam();
            sortParam.setColumn("empNo");
            sortParam.setOrderBy("asc");
            requestParam.setSort(sortParam);
        }

        DataPage<SysUserVo> page = new DataPage<SysUserVo>((long) requestParam.getCurrent(), (long) requestParam.getSize(), requestParam.getSort().getOrderItem(), SysUserVo.class);
        page = sysUserService.listByPage(page, requestParam.getData());

        // 绑定启用标志文本
        DataBindHelper.bindDataLabel(page.getRecords(), AvailableStatus.getMap(), "enabled", "enabledLabel");

        return new RetPage<SysUserVo>(page);
    }


    /**
     * 根据员工号获取员工id
     *
     * @param usernos
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "根据员工号获取员工id", notes = "根据员工号获取员工id", httpMethod = "POST")
    @PostMapping("/getUseridsForUserNo")
    public RetResult<?> getUseridsForUserNo(@RequestBody List<String> usernos) {
        List<String> ret = sysUserService.getUseridsForUserNo(usernos);
        return RetResult.ok(ret);
    }

    /**
     * 根据员工号获取员工手机号
     *
     * @param usernos
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)})
    @ApiOperation(value = "根据员工号获取员工手机号", notes = "根据员工号获取员工手机号", httpMethod = "POST")
    @PostMapping("/getPhoneListForUserNo")
    public RetResult<?> getPhoneListForUserNo(@RequestBody List<String> usernos) {
        List<String> ret = sysUserService.getPhoneListForUserNo(usernos);
        return RetResult.ok(ret);
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @PostMapping("/getusers")
    public RetResult<?> getusers() {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id value,first_name label");
        queryWrapper.lambda().eq(SysUser::getEnabled,1);
        queryWrapper.lambda().eq(SysUser::getDeleted,0);
        queryWrapper.lambda().ne(SysUser::getId,1);
        List<Map<String, Object>> ret = sysUserService.listMaps(queryWrapper);
        return RetResult.ok(ret);
    }

    /**
     * 导入用户
     */
    @PostMapping("upload")
    public RetResult<?> upload(MultipartFile file) throws IOException {
        // 读取excel
        List<SysUserUploadExcel> items = EasyExcel.read(file.getInputStream(), SysUserUploadExcel.class, null).autoCloseStream(true).sheet(0).headRowNumber(1).autoTrim(true).doReadSync();
        //对表格中字段名称转换成相应字段数值
        sysUserService.insertBatch(items);
        return RetResult.ok();
    }
    /**
     * 下载模板
     */
    @PostMapping("exportTemp")
    @ApiOperation("下载模板")
    public void exportTemp(HttpServletResponse response) throws Exception {
        List<SysUserUploadExcel> list = new ArrayList<>();
        list.add(new SysUserUploadExcel());
        ExcelUtils.exportExcelToTarget(response, null, list, SysUserUploadExcel.class);
    }



    /**
     * 根据角色id获取用户信息
     *
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "SysUserQuery", name = "sysUserQuery", value = "", required = true)})
    @ApiOperation(value = "根据角色id获取用户信息", notes = "根据角色id获取用户信息", httpMethod = "POST")
    @PostMapping("getUserListByRoleIds")
    public RetResult<?> getUserListByRoleIds(@RequestBody List<String> roleIds) {
//        ref_user_role_mapping
        List<SysUserWithRoleIdDTO> list = sysUserService.getUserListByRoleIds(roleIds);
        // 绑定启用标志文本
        DataBindHelper.bindDataLabel(list, AvailableStatus.getMap(), "enabled", "enabledLabel");
        return RetResult.ok(list);
    }
}
